package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.domain.StrategyTemplate;
import cn.wolfcode.luowowo.search.query.StrategySearchQuery;
import cn.wolfcode.luowowo.search.service.IStrategyEsService;
import cn.wolfcode.luowowo.search.service.repository.StrategyTemplateRepository;
import cn.wolfcode.luowowo.search.vo.StatisVO;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.*;

@Service
public class StrategyEsServiceImpl implements IStrategyEsService {

    @Autowired
    private StrategyTemplateRepository repository;


    @Override
    public void save(StrategyTemplate template) {
        repository.save(template);
    }

    @Override
    public List<Map<String, Object>> queryThemeCommend() {
        List<Map<String,Object>> data = new ArrayList<>();

        //步骤1:通过es 分组查询, 查询到主题列表: themeid themeName count/////
        List<StatisVO> list = this.getStatisVOList("themeId", "themeName", "themeGroup");

        //优化1: 排序 -- list集合排序
        Collections.sort(list, new Comparator<StatisVO>() {
            //比较器, 比较元素在集合中位置
            //compare 比较方法, 返回
            // < 0 : 表示小于
            // = 0 : 表示等于
            // > 0 : 表示大于
            @Override
            public int compare(StatisVO o1, StatisVO o2) {
                //倒序排
                Long ret = o2.getCount() - o1.getCount();
                return ret.intValue();
            }
        });

        //优化2: 取前面10
        if(list.size()> 10){
            list = list.subList(0, 10);
        }




        //步骤2:通过主题id: themeid查询目的地集合///////////////////////////
        Map<String,Object> map = null;
        for (StatisVO vo : list) {
            map = new HashMap<>();
            //vo 主题
            map.put("theme", vo);
            //某一个主题下面, 关联的目的地集合
            List<StatisVO> dests = this.getDestByThemeId(vo.getId());
            map.put("dests", dests);
            data.add(map);
        }
        //步骤3:通过步骤1,步骤2数据,组装成最终的data数据,并返回////////////////
        return data;
    }
    //通过主题id, 查询目的地集合
    private List<StatisVO> getDestByThemeId(Long themeId) {
        List<StatisVO> vos = new ArrayList<>();
        List<StrategyTemplate> templates = repository.findByThemeId(themeId);
        //上面查询查到时 es攻略list集合, 前面需要知识目的id 目的地name

        //优化3: 目的地去除重复
        List<String> list = new ArrayList<>();

        // 广州, 广州, 广州
        for (StrategyTemplate template : templates) {
            if(!list.contains(template.getDestName())){
                StatisVO vo = new StatisVO();
                vo.setId(template.getId());
                vo.setName(template.getDestName());
                vos.add(vo);
                list.add(template.getDestName());
            }
        }
        return vos;
    }

    //统计分组集合
    private List<StatisVO> getStatisVOList(String isField,String nameField,String groupName){

        //分组列对象集合
        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();
        TermsValuesSourceBuilder idSource = new TermsValuesSourceBuilder("id");
        idSource.field(isField);
        TermsValuesSourceBuilder nameSource = new TermsValuesSourceBuilder("name");
        nameSource.field(nameField);
        sources.add(idSource);
        sources.add(nameSource);

        //构造分组语法
        CompositeAggregationBuilder aggregationBuilder
                = new CompositeAggregationBuilder(groupName, sources);

        //es查询语句构建类
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.addAggregation(aggregationBuilder);
        //分页
        builder.withPageable(PageRequest.of(0, 1));
        //明确指定查那个索引, 哪个类型
        builder.withIndices(StrategyTemplate.INDEX_NAME);
        builder.withTypes(StrategyTemplate.TYPE_NAME);


        //执行查询语句, 返回结果
        AggregatedPage<StrategyTemplate> search = (AggregatedPage<StrategyTemplate>)
                repository.search(builder.build());
        InternalComposite themeGroup = search.getAggregations().get(groupName);

        List<StatisVO> list = new ArrayList<>();
        for (CompositeAggregation.Bucket bucket : themeGroup.getBuckets()) {
            Long id  = Long.parseLong(bucket.getKey().get("id").toString());
            String name= bucket.getKey().get("name").toString();
            Long count = bucket.getDocCount();

            StatisVO vo = new StatisVO();
            vo.setCount(count);
            vo.setId(id);
            vo.setName(name);
            list.add(vo);
        }
        return list;
    }

    @Override
    public List<StatisVO> queryConditionChinas() {
        return this.getStatisVOList("provinceId","provinceName","provinceGroup");
    }

    @Override
    public List<StatisVO> queryConditionAbroads() {
        return this.getStatisVOList("countryId","countryName","countryGroup");
    }

    @Override
    public List<StatisVO> queryConditionThemes() {
        return this.getStatisVOList("themeId","themeName","themeGroup");
    }

    @Override
    public Page query(StrategySearchQuery qo) {
        TermQueryBuilder query = null;
        PageRequest of = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, qo.getOrderBy());

        if(qo.getType() == StrategySearchQuery.CONDITION_TYPE_COUNTRY){
            query = QueryBuilders.termQuery("countryId",qo.getTypeValue());
        }else if(qo.getType() == StrategySearchQuery.CONDITION_TYPE_PROVINCE){
            query = QueryBuilders.termQuery("provinceId",qo.getTypeValue());

        }else if(qo.getType() == StrategySearchQuery.CONDITION_TYPE_THEME){
            query = QueryBuilders.termQuery("themeId",qo.getTypeValue());

        }
        if(query == null){
            return repository.findAll(of);
        }else{
            return repository.search(query,of);
        }
    }

    @Override
    public List<StrategyTemplate> findByDestName(String destName) {
        return repository.findByDestName(destName);
    }
}
